const path = require("path")
const fs = require('fs')
const express = require('express')
const os = require('os')
const cors = require('cors')
const appRouter = require('./routers/app')
const userRouter = require('./routers/user')
const {expressjwt} = require('express-jwt')
const https = require('https')

const app = express();
app.use(cors())
// app.use((req, res, next) => {
//     res.set("Access-Control-Allow-Origin", "*");
//     next();
// })
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, '../font/dist')));
app.use(express.static(path.join(__dirname, 'pics')));
app.use(express.static(path.join(__dirname, 'static')));
app.use(express.static(path.join(__dirname, 'avatars')));

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended:false}));

app.use((req, res, next)=>{
    res.cc = function (msg, status=1) {
        res.send({
            status,
            msg: msg instanceof Error ? msg.message : msg
        })
    }
    next();
})

const secretKey = 'yxy_s_secret_key';
// 使用中间件解码，之后req上就会挂载一个user属性，用于保存之前token里保存的用户信息
app.use(expressjwt({secret: secretKey, algorithms:['HS256']}).unless({path: [/^\/api\//]}))

app.use("/api", appRouter);
app.use("/user", userRouter);

// 注册全局错误中间件，用于捕获token解析失败时的情况
app.use((err, req, res, next) => {
    switch (true) {
        // case err instanceof joi.ValidationError:
        //     res.cc('验证失败');
        //     break;

        case err.name === 'UnauthorizedError':
            res.cc( '登录已过期，请重新登录', 2);
            break;

        default:
            res.cc(err);
    }
    next();
})

function getIPv4(){
    const interfaces = os.networkInterfaces();//获取网络接口列表
    const ipv4s = [];//同一接口可能有不止一个IP4v地址，所以用数组存

    Object.keys(interfaces).forEach(function (key){
        interfaces[key].forEach(function (item){

            //跳过IPv6 和 '127.0.0.1'
            if ( 'IPv4' !== item.family || item.internal !== false )return;

            ipv4s.push(item.address);//可用的ipv4s加入数组
            console.log(key+'--'+item.address);
        })
    })

    return ipv4s[2];//返回一个可用的即可
}

app.listen("8001", ()=>{
    console.log("服务器已开启，请通过以下网址访问：")
    console.log(getIPv4()+':8001')
})

// const server = https.createServer({
//     pfx: fs.readFileSync(path.join(__dirname, 'keys','...pfx')),
//     passphrase: ''
// }, app)
//
// server.listen(443, () => {
//     console.log("服务器已开启，请通过以下网址访问：")
//     // console.log('https://picsshow.site')
// })
